package com.crcc.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author sxq
 * @Description:获取上下文配置
 * @create 2020-09-21 15:00
 */

@Component
public class SpringContextUtil implements ApplicationContextAware {
	private static ApplicationContext applicationContext;

	@Override
    @Autowired
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	/**
	 * 获取applicationContext
	 *
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}


	public static Object getBean(String beanId) {
		return getApplicationContext().getBean(beanId);
	}

	public static Object getProperty(String beanName) {
		return getApplicationContext().getEnvironment().getProperty(beanName);
	}


	/**
	 * 在spring容器初始化前，获取根据配置文件的名称与key获取对应的属性值
	 * @param propertiseName 配置文件的名称
	 * @param key 要获取的属性
	 * @return 属性值
	 * @throws IOException
	 */
	  public static Object getPropertyBeforeStarted(String propertiseName ,String key) throws IOException {
		  InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiseName);
		  Properties prop = new Properties();
		  prop.load(stream);
		  return prop.getProperty(key);
	  }

	  public static Properties getPropertys(String propertiseName) throws IOException {
		  InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiseName);
		  Properties prop = new Properties();
		  prop.load(stream);
		  return prop;
	  }

}
